package com.onpositive.funkytable;

import java.util.ArrayList;

import com.onpositive.funkytable.model.ICompositeModelElement;
import com.onpositive.funkytable.model.IModelElement;
import com.onpositive.funkytable.swt.ISWTControl;

public class DefaultTableBuilder implements IFunkyTableBuilder {

	@Override
	public IFunkyComposite buildUI(IControlFactory factory, int width,
			int height, ICompositeModelElement model) {
		IFunkyComposite createComposite = factory
				.createComposite(IFunkyComposite.VERTICAL);
		createComposite.setStyle(factory.sectionStyle());

		IModelElement[] children = model.children();
		ArrayList<BuildedSectionModel> section = new ArrayList<BuildedSectionModel>();
		for (IModelElement l : children) {
			if (l instanceof ICompositeModelElement) {
				BuildedSectionModel sm = new BuildedSectionModel(factory,
						(ICompositeModelElement) l);
				section.add(sm);
			}
		}
		double w[] = new double[] { 0.25, 0.33, 0.5, 0.66, 0.75 };
		l2: for (int a = 0; a < section.size(); a++) {
			BuildedSectionModel buildedSectionModel = section.get(a);
			buildedSectionModel.build(width);
			if (buildedSectionModel.weight > 0) {
				for (int b = 0; b < w.length; b++) {
					buildedSectionModel.build((int) (width * w[b]));
					if (buildedSectionModel.weight > 0
							&& a < section.size() - 1) {
						BuildedSectionModel buildedSectionModel2 = section
								.get(a + 1);
						buildedSectionModel2.build((int) (width * (1 - w[b])));
						if (buildedSectionModel2.weight > 0) {
							IFunkyComposite createComposite2 = factory
									.createComposite(IFunkyComposite.HORIZONTAL);
							createComposite2.add(buildedSectionModel.composite,
									new LayoutParams((int) (width * w[b]),
											ILayoutParams.WRAP_WIDTH));
							createComposite2.add(
									buildedSectionModel2.composite,
									new LayoutParams(
											(int) (width * (1 - w[b])),
											ILayoutParams.WRAP_WIDTH));
							createComposite.add(createComposite2,
									new LayoutParams(ILayoutParams.FILL_PARENT,
											ILayoutParams.WRAP_WIDTH));
							((ISWTControl) createComposite2).layout(width);
							a++;
							continue l2;
						}
					}
				}
			}
			createComposite.add(buildedSectionModel.composite,
					new LayoutParams(ILayoutParams.FILL_PARENT,
							ILayoutParams.WRAP_WIDTH));

		}
		return createComposite;
	}

}
